import requests, pymysql, pandas, configparser, os


class Conf:
    conf = configparser.ConfigParser()  # 类变量

    def read_entry(self):  # 读入口配置文件
        Conf.conf.read('entry.ini', encoding='utf-8')
        self.__which_server =Conf.conf.get('entry', 'which_server')
        self.__which_db = Conf.conf.get('entry', 'which_db')
        # print(self.__which_server, self.__which_db)

    def read_server_conf(self):  # 读接口服务器信息  将接口服务器信息组装成http://IP:port的形式，向类外公开，后面用例中可以使用
        Conf.conf.read('server.conf', encoding='utf-8')
        ip = Conf.conf.get(self.__which_server, 'ip')
        port = Conf.conf.get(self.__which_server, 'port')
        self.host = {f'http://{ip}:{port}'}
        # print(self.host)

    def read_db_conf(self):  # 读数据库
        Conf.conf.read('db.conf', encoding='utf-8')
        host = Conf.conf.get(self.__which_db, 'host')
        db = Conf.conf.get(self.__which_db, 'db')
        user = Conf.conf.get(self.__which_db, 'user')
        passwd = Conf.conf.get(self.__which_db, 'passwd')
        self.dbinfo = {'host': host, 'db': db, 'user': user, 'passwd': passwd}
        # print(self.dbinfo)

    def __init__(self):  # 构造方法
        self.read_entry()
        self.read_server_conf()
        self.read_db_conf()


# def read_sqls(sqlfiles): #读指定的sql文件sqlfile将所有有效sql语句存入列表并返回；如果不给参数则读取当前文件夹中所有sql文件中的sql语句
# file=open(sqlfiles,'r',encoding='utf-8')
# sqls=[]  #存所有有效sql语句的列表
# for sql in file:
#     if sql.strip() and not sql.startswith('--'):
#         sqls.append(sql.strip())
# return sqls
# print(read_sqls('login.sql'))

def read_sqls(*sqlfiles):
    if not sqlfiles:  # 没给参数
        sqlfiles = [i for i in os.listdir() if i.endswith('.sql')]
    print(sqlfiles)
    sqls = []
    # 否则，sqlfiles中本来就存着很多文件名
    for sfile in sqlfiles:
        file = open(sfile, 'r', encoding='utf-8')
        for sql in file:
            if sql.strip() and not sql.startswith('--'):
                sqls.append(sql.strip())
    return sqls


# print(read_sqls('login.sql'))


print(read_sqls())

class DB:  # 构造方法，用于连接数据库，将数据库连接对象和游标存入私有成员变量
    def __init__(self):  # 构造方法
        dbinfo = Conf().dbinfo
        self.__conn = pymysql.connect(**dbinfo)
        self.__cursor = self.__conn.cursor()

    def init_db(self,*sqlfiles):  # 初始化数据库
        sqls = read_sqls(*sqlfiles)
        # print(sqls)
        for sql in sqls:
            self.__cursor.execute(sql)
        self.__conn.commit()
        self.__conn.close()


if __name__ == '__main__':  # 调试代码
    # Conf().read_entry()  # Conf()创建一个匿名对象
    # 写法1：没写构造之前
    # a=Conf()
    # a.read_entry()
    # a.read_server_conf()
    # a.read_db_conf()
    # 写法2：使用构造
    # a = Conf()
    # print(a.host, a.dbinfo)
    a = DB()
    a.init_db('login.sql')  # sqlfiles=(),read_sqls(*()),read_sqls()
